#include <iostream>
#include <functional>
#include <unordered_map>
#include "../../../../include/muduo/net/TcpClient.h"
#include "../../../../include/muduo/net/EventLoopThread.h"
#include "../../../../include/muduo/net/TcpConnection.h"
#include "../../../../include/muduo/base/CountDownLatch.h"
using namespace std;


class TranslateClient
{
public:
    TranslateClient(const std::string& ip, int port)
        : _latch(1)
        , _client(_baseloop.startLoop(), muduo::net::InetAddress(ip, port), "TcpClient")
    {
        auto fun1 = bind(&TranslateClient::onConnect, this, placeholders::_1);
        _client.setConnectionCallback(fun1);
        auto fun2 = bind(&TranslateClient::onMessage, this, placeholders::_1, placeholders::_2, placeholders::_3);
        _client.setMessageCallback(fun2);
    }

    void connect()
    {
        _client.connect();
        _latch.wait(); //阻塞等待，直到连接建立成功
    }

    void send(const std::string& str)
    {
        if (_conn->connected())
            _conn->send(str);
    }

private:
    //连接建立成功时的回调函数，连接建立成功后，唤醒阻塞
    void onConnect(const muduo::net::TcpConnectionPtr& conn)
    {
        if (conn->connected())
        {
            _latch.countDown(); //唤醒阻塞
            _conn = conn;
        }
        else 
        {
            std::cout << "连接断开!!" << endl;
            _conn.reset();
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf,
        muduo::Timestamp timestamp)
    {
        string res = buf->retrieveAllAsString();
        std::cout << "翻译结果：" << res << endl;
    }

private:
    muduo::CountDownLatch _latch;
    muduo::net::EventLoopThread _baseloop;
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
};

int main()
{
    TranslateClient client("127.0.0.1", 8080);
    client.connect();

    while (true)
    {
        string str;
        cout << "请输入要翻译的单词：";
        getline(cin, str);
        if (str == "quit")
            break;

        client.send(str);
        sleep(1);
    }

    return 0;
}